<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LLM 聊天界面 (原生实现)</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --user-bubble: #409EFF;
            --bot-bubble: #e9e9eb;
            --error-bubble: #fef0f0;
            --error-text: #f56c6c;
            --background: #f0f2f5;
            --header-height: 60px;
            --footer-height: 70px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: var(--background);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 768px;
            height: 90vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            border-radius: 12px;
            overflow: hidden;
            background: white;
        }

        .chat-header {
            height: var(--header-height);
            background-color: var(--primary-color);
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }

        .chat-header h1 {
            font-size: 1.25rem;
            font-weight: bold;
        }

        .header-controls {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .clear-btn {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 14px;
            padding: 5px 10px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .clear-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .mode-select {
            width: 120px;
            padding: 8px 12px;
            border-radius: 4px;
            border: none;
            background: rgba(255, 255, 255, 0.15);
            color: white;
            cursor: pointer;
        }

        .mode-select option {
            background: white;
            color: #333;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background-color: #fcfcfc;
        }

        .message-row {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
        }

        .message-row.user {
            justify-content: flex-end;
        }

        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 14px;
            margin-right: 12px;
        }

        .user .avatar {
            display: none;
        }

        .bot .avatar {
            background-color: var(--primary-color);
        }

        .error .avatar {
            background-color: var(--error-text);
        }

        .message-bubble {
            padding: 10px 15px;
            border-radius: 15px;
            max-width: 70%;
            word-wrap: break-word;
        }

        .message-bubble.user {
            background-color: var(--user-bubble);
            color: white;
        }

        .message-bubble.bot {
            background-color: var(--bot-bubble);
            color: #303133;
        }

        .message-bubble.error {
            background-color: var(--error-bubble);
            color: var(--error-text);
            border: 1px solid #fde2e2;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .typing-indicator .dot {
            width: 8px;
            height: 8px;
            background-color: #909399;
            border-radius: 50%;
            animation: pulse 1.4s infinite ease-in-out both;
        }

        .typing-indicator .dot:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator .dot:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes pulse {
            0%, 80%, 100% {
                transform: scale(0);
            }
            40% {
                transform: scale(1.0);
            }
        }

        .chat-footer {
            height: var(--footer-height);
            padding: 15px 20px;
            border-top: 1px solid #e4e7ed;
            background: #fff;
        }

        .input-container {
            display: flex;
            height: 48px;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .message-input {
            flex: 1;
            border: none;
            padding: 0 15px;
            font-size: 16px;
            outline: none;
            background: #f5f7fa;
        }

        .message-input:focus {
            background: white;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }

        .send-btn {
            width: 48px;
            background: var(--user-bubble);
            border: none;
            color: white;
            cursor: pointer;
            font-size: 18px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .send-btn:disabled {
            background: #c0c4cc;
            cursor: not-allowed;
        }

        .welcome-message {
            text-align: center;
            color: #666;
            margin-top: 30px;
            font-size: 14px;
        }

        @media (max-width: 600px) {
            .chat-container {
                height: 95vh;
            }

            .chat-header h1 {
                font-size: 1rem;
            }

            .message-bubble {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h1>LLM 聊天机器人</h1>
            <div class="header-controls">
                <button class="clear-btn" id="clearBtn">
                    <i class="fas fa-trash-alt"></i> 清空记录
                </button>
                <select class="mode-select" id="chatType">
                    <option value="kb_chat">知识库</option>
                    <option value="chat">代理/工具</option>
                </select>
            </div>
        </div>

        <div class="chat-messages" id="chatMessages">
            <div class="message-row bot">
                <div class="avatar">
                    <i class="fas fa-comment-dots"></i>
                </div>
                <div class="message-bubble bot">
                    <div>您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！</div>
                </div>
            </div>
        </div>

        <div class="chat-footer">
            <div class="input-container">
                <input
                    type="text"
                    class="message-input"
                    id="userInput"
                    placeholder="在这里输入您的问题..."
                >
                <button class="send-btn" id="sendBtn" disabled>
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // DOM元素
            const chatMessages = document.getElementById('chatMessages');
            const userInput = document.getElementById('userInput');
            const sendBtn = document.getElementById('sendBtn');
            const clearBtn = document.getElementById('clearBtn');
            const chatType = document.getElementById('chatType');

            // 状态变量
            let isLoading = false;
            let conversationId = null;
            const messages = [
                { sender: 'bot', text: '您好！欢迎使用 LLM 聊天机器人。请选择一个聊天模式，然后开始提问吧！' }
            ];

            // 输入框事件
            userInput.addEventListener('input', () => {
                sendBtn.disabled = isLoading || !userInput.value.trim();
            });

            // 发送消息
            function sendMessage() {
                const text = userInput.value.trim();
                if (!text || isLoading) return;

                // 添加用户消息
                addMessage('user', text);
                userInput.value = '';
                sendBtn.disabled = true;

                // 模拟API调用
                simulateApiCall(text);
            }

            // 添加消息到聊天界面
            function addMessage(sender, text) {
                messages.push({ sender, text });
                renderMessages();
                scrollToBottom();
            }

            // 渲染所有消息
            function renderMessages() {
                chatMessages.innerHTML = '';

                messages.forEach(msg => {
                    const messageRow = document.createElement('div');
                    messageRow.className = `message-row ${msg.sender}`;

                    if (msg.sender !== 'user') {
                        const avatar = document.createElement('div');
                        avatar.className = 'avatar';

                        const icon = document.createElement('i');
                        icon.className = msg.sender === 'bot' ? 'fas fa-comment-dots' : 'fas fa-exclamation-triangle';
                        avatar.appendChild(icon);

                        messageRow.appendChild(avatar);
                    }

                    const bubble = document.createElement('div');
                    bubble.className = `message-bubble ${msg.sender}`;

                    const content = document.createElement('div');
                    content.textContent = msg.text;
                    bubble.appendChild(content);

                    messageRow.appendChild(bubble);
                    chatMessages.appendChild(messageRow);
                });

                // 添加加载指示器（如果正在加载）
                if (isLoading) {
                    const loadingRow = document.createElement('div');
                    loadingRow.className = 'message-row bot';

                    const avatar = document.createElement('div');
                    avatar.className = 'avatar';
                    const icon = document.createElement('i');
                    icon.className = 'fas fa-comment-dots';
                    avatar.appendChild(icon);
                    loadingRow.appendChild(avatar);

                    const bubble = document.createElement('div');
                    bubble.className = 'message-bubble bot';

                    const typing = document.createElement('div');
                    typing.className = 'typing-indicator';

                    for (let i = 0; i < 3; i++) {
                        const dot = document.createElement('div');
                        dot.className = 'dot';
                        typing.appendChild(dot);
                    }

                    bubble.appendChild(typing);
                    loadingRow.appendChild(bubble);
                    chatMessages.appendChild(loadingRow);
                }
            }

            // 滚动到底部
            function scrollToBottom() {
                setTimeout(() => {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }, 10);
            }

            // 模拟API调用
            function simulateApiCall(query) {
                isLoading = true;
                renderMessages();
                scrollToBottom();

                // 模拟网络延迟
                setTimeout(() => {
                    try {
                        // 随机决定是成功回复还是模拟错误
                        if (Math.random() > 0.2) {
                            // 成功回复
                            const responses = [
                                "大型语言模型（LLM）是一种基于深度学习的自然语言处理模型，能够理解和生成人类语言。",
                                "知识库模式允许我根据预加载的文档和信息来回答您的问题，提供更准确的领域知识。",
                                "在代理/工具模式下，我可以使用外部工具和API来执行任务，比如计算、搜索或调用其他服务。",
                                "我使用了Transformer架构，这是一种基于自注意力机制的深度学习模型，特别适合处理序列数据。",
                                "我的训练数据包括大量书籍、文章和网页内容，但请注意我的知识截止于2023年。",
                                "您可以通过输入更具体的问题来获得更精确的回答。例如，问'什么是神经网络？'而不是'解释一下AI'。",
                                "我能够理解上下文，所以您可以继续提问而无需重复之前的问题内容。",
                                "如果您没有得到满意的答案，尝试换一种方式提问或提供更多背景信息。"
                            ];

                            const randomResponse = responses[Math.floor(Math.random() * responses.length)];
                            addMessage('bot', randomResponse);
                        } else {
                            // 模拟错误
                            const errors = [
                                "请求超时，请稍后再试",
                                "服务器暂时不可用，请稍后再试",
                                "处理您的请求时发生错误",
                                "无法连接到AI服务"
                            ];
                            const randomError = errors[Math.floor(Math.random() * errors.length)];
                            addMessage('error', randomError);
                        }
                    } catch (error) {
                        addMessage('error', `处理请求时发生错误: ${error.message}`);
                    } finally {
                        isLoading = false;
                        renderMessages();
                        scrollToBottom();
                    }
                }, 1500 + Math.random() * 2000); // 1.5-3.5秒的随机延迟
            }

            // 清空聊天
            function clearChat() {
                messages.length = 0;
                messages.push({ sender: 'bot', text: '聊天记录已清空，可以开始新的对话了。' });
                conversationId = null;
                renderMessages();
                scrollToBottom();
            }

            // 事件监听器
            sendBtn.addEventListener('click', sendMessage);
            userInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !sendBtn.disabled) {
                    sendMessage();
                }
            });
            clearBtn.addEventListener('click', clearChat);

            // 初始渲染
            renderMessages();
        });
    </script>
</body>
</html>